package com.shujia.custom.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.lazy.LazyString;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class UDTFDemo2 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        ArrayList<String> colNameList = new ArrayList<>();
        colNameList.add("id");
        colNameList.add("time");
        colNameList.add("value");

        ArrayList<ObjectInspector> colTypeList = new ArrayList<>();
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        colTypeList.add(PrimitiveObjectInspectorFactory.javaLongObjectInspector);

        return ObjectInspectorFactory.getStandardStructObjectInspector(colNameList, colTypeList);
    }

    //输入一条13列数据，第一列是监测点编号，从第二列开始都是检测值
    //a,1,2,3,4,5,6,7,8,9,10,11,12
    //每一条记录都会执行一次process方法
    @Override
    public void process(Object[] args) throws HiveException {
        String id = ((LazyString)args[0]).getWritableObject().toString();
        Object[] cols = new Object[3];
        cols[0] = id;
        long t = 0;
        for(int i=1;i<args.length;i++){
            cols[1] = t+"时";
            cols[2] = Long.parseLong(((LazyString)args[i]).getWritableObject().toString());
            t+=2;
            forward(cols);
        }
    }

    @Override
    public void close() throws HiveException {

    }
}
